//
// Created by lingzhitech on 25-9-29.
//



#include <fstream>

#include <iostream>
#include <map>
#include <sstream>
#include <string>
#include <unistd.h>
#include <linux/limits.h>

std::map<std::string, std::string> buildMap(std::ifstream &map_file)
{
    std::map< std::string, std::string> trans_map; // holds the transformations
    std::string key; // a word to transform
    std::string value; // phrase to use instead
    // read the first word into key and the rest of the line into value
    while (map_file >> key && getline(map_file, value))
        if (value.size() > 1) // check that there is a transformation
            trans_map[key] = value.substr(1); // skip leading space
        else
            throw std::runtime_error("no rule for " + key);
    return trans_map;
}

const std::string &
transform(const std::string &s, const std::map<std::string, std::string> &m)
{
    // the actual map work; this part is the heart of the program
    auto map_it = m.find(s);
    // if this word is in the transformation map
    if (map_it != m.cend())
        return map_it->second; // use the replacement word
    else
        return s; // otherwise return the original unchanged
}
void word_transform(std::ifstream &map_file, std::ifstream &input)
{
    auto trans_map = buildMap(map_file); // store the transformations
    std::string text; // hold each line from the input
    while (getline(input, text)) { // read a line of input
        std::istringstream stream(text); // read each word
        std::string word;
        bool firstword = true; // controls whether a space is printed
        while (stream >> word) {
            if (firstword)
                firstword = false;
            else
                std::cout << " "; // print a space between words
            // transform returns its first argument or its transformation
            std::cout << transform(word, trans_map); // print the output
        }
        std::cout << std::endl; // done with this line of input
    }
}
int main() {
    // char buf[PATH_MAX];   // 缓冲区
    // if (getcwd(buf, sizeof(buf)) != nullptr) {
    //     std::cout << "当前工作目录: " << buf << std::endl;
    // } else {
    //     perror("getcwd error");
    // }
    std::ifstream map_file("ch11/word_transformation_map/map_file");
    std::ifstream input("ch11/word_transformation_map/input");
    word_transform(map_file, input);
}